<?php
require_once 'seedniaenvs.php';
include 'log4php/Logger.php';
require 'Slim/Slim.php';
require 'restutil.php';

require_once APPROOT.'/application/classes/util/session.php';
require_once APPROOT.'/application/classes/util/datetime.php';
require_once APPROOT.'/application/classes/rest/client.php';
require_once APPROOT.'/application/classes/rest/response.php';
require_once APPROOT.'/application/classes/service/RestServiceStubBase.php';
require_once APPROOT.'/application/classes/service/GenericSeedniaServiceStub.php';

define('STATUS_DELETED', -1);
define('STATUS_ASSIGNED', 1);
define('STATUS_STARTED', 2);
define('STATUS_BLOCKED', 3);
define('STATUS_COMPLETED', 4);
define('STATUS_COMPLETED_HIDDEN', 5);

session_start(); // start up your PHP session! 

Logger::configure('log4php.xml');

$app = new Slim(array(
    'log.enable' => true,
    'log.path' => './logs',
    'log.level' => 3,
));

//GET route
$app->get('/actionable/:sid', 'getActionable') ;
$app->post('/actionable', 'postActionable') ;
$app->put('/actionable/:sid', 'putActionable') ;
$app->delete('/actionable/:sid', 'deleteActionable') ;
$app->get('/user/actionables/:userSid', 'getActionablesOfUser') ;
$app->get('/project/actionables/:projectSid', 'getActionablesOfProject') ;

$app->run();

function getActionableService()
{
	$actionableService = new Service_GenericSeedniaServiceStub(WSROOT.WSCONTEXT.'/'.SERVICE_ACTIONABLE.'/', ACCESS_TOKEN);
	return $actionableService;
}

function getActionable($sid) {
    $logger = Logger::getLogger("seednia");
    $logger->info("at getActionable(".$sid.")");

    $app = Slim::getInstance();
    $response = $app->response();
    $response['Content-Type'] = 'application/json';
	$response['X-Powered-By'] = 'Seednia';
	
	$actionableService = getActionableService();
	$actionable = $actionableService->getByXid($sid);
	
    $result = json_encode($actionable);
    echo $result;
};

function postActionable() {
    $logger = Logger::getLogger("seednia");
    $logger->info("at postActionable()");

	try {
		$request = Slim::getInstance()->request();
		$body = $request->getBody();
		$record = json_decode($body, true);
		
		normalizeRecord($record);
		
		$userInfo = Util_Session::getUserInfo();
		$record['creatorSid'] = $userInfo['userSid'];

		$actionableService = getActionableService();
		$sid = $actionableService->add($record);
		$record['sid'] = $sid;
		echo json_encode($record);
	} catch (Exception $e) {
		echo '{"error":{"text":'. $e->getMessage() .'}}';
		$logger->error($e);
	}
};

function putActionable($sid) {
    $logger = Logger::getLogger("seednia");
    $logger->info("at putActionable(".$sid.")");
	
	try {
		$request = RestUtil::getRequest();
		
		$body = $request->getBody();
		$record = json_decode($body, true);
		$record['sid'] = $sid;

		normalizeRecord($record);
		
		if ($record['status'] == STATUS_COMPLETED) {
			$record['actualDate'] = Util_Datetime::format_std(new DateTime);
		}

		$actionableService = getActionableService();
		$result = $actionableService->update($record);
		echo json_encode($record);
	} catch (Exception $e) {
		echo '{"error":{"text":'. $e->getMessage() .'}}';
		$logger->error($e);
	}
};

function deleteActionable($sid) {
    $logger = Logger::getLogger("seednia");
    $logger->info("at deleteactionable (".$sid.")");

	try {
		$actionableService = getActionableService();
		$actionableService->deleteBySid((int)$sid);
	} catch (Exception $e) {
		echo '{"error":{"text":'. $e->getMessage() .'}}';
		$logger->error($e);
	}
};

function getActionablesOfUser($userSid) {
    $logger = Logger::getLogger("seednia");
	
	$sessionUserSid = null;
	if ( isset($_SESSION[SNAME_USER])) {
		$userInfo = $_SESSION[SNAME_USER];
		$sessionUserSid = $userInfo['userSid'];
	}
	
    $logger->info("at getActionablesOfUser(".$userSid.")");
	$logger->info("   userSid in sesssion=".$sessionUserSid);

    $app = Slim::getInstance();
    $response = $app->response();
    $response['Content-Type'] = 'application/json';
	$response['X-Powered-By'] = 'Seednia';
	
	$actionableService = getActionableService();
	
	$actionableCriteria = array('creatorSid'=> $userSid);
	try {
		$actionables = $actionableService->getList($actionableCriteria, 0, 20, '');
		$result = json_encode($actionables);
		echo $result;
	} catch (Exception $e) {
		echo '{"error":{"text":'. $e->getMessage() .'}}';
		$logger->error($e);
	}
};


function getActionablesOfProject($projectSid) {
    $logger = Logger::getLogger("seednia");
    $logger->info("at getActionablesOfProject(".$projectSid.")");

    $app = Slim::getInstance();
    $response = $app->response();
    $response['Content-Type'] = 'application/json';
	$response['X-Powered-By'] = 'Seednia';
	
	$actionableService = getActionableService();
	
	$actionableCriteria = array('projectSid'=> $projectSid);
	try {
		$actionables = $actionableService->getList($actionableCriteria, 0, 20, '');
		$result = json_encode($actionables);
		echo $result;
	} catch (Exception $e) {
		echo '{"error":{"text":'. $e->getMessage() .'}}';
		$logger->error($e);
	}
};

function normalizeRecord(&$record)
{
	if (array_key_exists('projectName', $record))
		unset($record['projectName']);
	if (array_key_exists('projectId', $record))
		unset($record['projectId']);
	if (array_key_exists('creatorId', $record))
		unset($record['creatorId']);

	//yyyy-MM-dd'T'HH:mm:ss.SZ
	if (!array_key_exists('createDt', $record))
		$record['createDt'] = Util_Datetime::format_std(new DateTime);
	else 
		$record['createDt'] = substr($record['createDt'], 0, 19);

	if (!array_key_exists('lastModifiedDt', $record))
		$record['lastModifiedDt'] = Util_Datetime::format_std(new DateTime);
	else 
		$record['lastModifiedDt'] = substr($record['lastModifiedDt'], 0, 19);

	if (isset($record['baselineDate']))
		$record['baselineDate'] = substr($record['baselineDate'], 0, 19);

	if (isset($record['actualDate']))
		$record['actualDate'] = substr($record['actualDate'], 0, 19);
	return $record;
}

////////// TESTS //////////

function getActionableTest($sid) {
    $logger = Logger::getLogger("seednia");
    $logger->info("at getactionable");

    $app = Slim::getInstance();
    $response = $app->response();
    $response['Content-Type'] = 'application/json';
	$response['X-Powered-By'] = 'Seednia';
	
	
	$actionable = new stdClass();
	$actionable->creatorDto = new stdClass();
	$actionable->creatorDto->sid = 1;
	$actionable->creatorDto->displayName = "Young Suk";
	$actionable->creatorSid = 1;
	$actionable->name = "Get Document";
	$actionable->description = "Hello World";
	
    $result = json_encode($actionable);
    echo $result;
};

function getActionablesOfProjectTest($projectSid) {
    $logger = Logger::getLogger("seednia");
    $logger->info("at getactionable");

    $app = Slim::getInstance();
    $response = $app->response();
    $response['Content-Type'] = 'application/json';
	$response['X-Powered-By'] = 'Seednia';
	$result = <<<EOT
[{ "sid": 1, "name": "FROM REST nice test", "description": "Difficult Actionable", "creatorDisplayName": "REST Ahn", "createDt": "2012/1/3", "creatorProfileImageSid": 58, "projectSid": 11, "projectName":"Seednia" },
{ "sid": 2, "name": "FROM REST 22", "description": "FROM REST nice test", "creatorDisplayName": "REST 2", "createDt": "2012/1/3", "creatorProfileImageSid": 58, "projectSid": 11, "projectName":"Seednia" }]
EOT;
	echo $result;
};